package com.eastedu.report.template;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.common.page.PageResult;
import com.eastedu.common.page.Pageable;
import com.eastedu.exception.ServiceException;
import com.eastedu.jdbc.mybatis.utils.CustomSqlHelper;
import com.eastedu.report.common.model.po.TemplateConfigPO;
import com.eastedu.report.common.model.vo.ReportTemplateUploadVO;
import com.eastedu.report.common.util.FileUtil;
import com.eastedu.report.mapper.TemplateConfigMapper;
import com.eastedu.template.core.template.ReportTempleProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Objects;


/**
 * 模版配置
 *
 * @author luozhenzhong
 */
@Service
@Slf4j
public class DefaultReportTemplateConfiguration implements ReportTemplateConfiguration, ReportTempleProvider {
    private final TemplateConfigMapper configMapper;
    private static final String TEMPLATE_PATH = "report-template/{0}.docx";

    /**
     * Instantiates a new Default report template configuration.
     *
     * @param configMapper the config mapper
     */
    public DefaultReportTemplateConfiguration(TemplateConfigMapper configMapper) {
        this.configMapper = configMapper;
    }

    @Override
    public void add(ReportTemplateUploadVO templateUploadVO) throws IOException {
        MultipartFile file = templateUploadVO.getFile();
        String contentType = file.getContentType();
        if (!FileUtil.isWord(contentType)) {
            throw new ServiceException("仅支持word文档");
        }
        TemplateConfigPO po = new TemplateConfigPO();
        po.setOriginalFileName(file.getOriginalFilename());
        po.setContent(file.getBytes());
        po.setSize(file.getSize());
        po.setTemplateCode(templateUploadVO.getTemplateCode());
        po.setTemplateName(templateUploadVO.getTemplateName());
        po.setUpdateTime(System.currentTimeMillis());
        configMapper.insert(po);
    }

    @Override
    public void update(Long templateId, MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        if (!FileUtil.isWord(contentType)) {
            throw new ServiceException("仅支持word文档");
        }
        TemplateConfigPO po = configMapper.selectById(templateId);
        if (Objects.isNull(po)) {
            throw new ServiceException("模版'" + templateId + "'不存在");
        }
        po.setOriginalFileName(file.getOriginalFilename());
        po.setContent(file.getBytes());
        po.setSize(file.getSize());
        po.setUpdateTime(System.currentTimeMillis());
        configMapper.updateById(po);
    }

    @Override
    public void delete(Long templateId) {
        configMapper.deleteById(templateId);
    }

    @Override
    public TemplateConfigPO get(Long templateId) {
        TemplateConfigPO po = configMapper.selectById(templateId);
        if (Objects.isNull(po)) {
            throw new ServiceException("模版'" + templateId + "'不存在");
        }
        return po;
    }

    @Override
    public PageResult<TemplateConfigPO> list(Pageable pageable) {
        return CustomSqlHelper.<TemplateConfigPO, TemplateConfigPO>pageQuery(pageable, page -> configMapper.selectPage(page, Wrappers.emptyWrapper()));
    }


    @Override
    public Long count() {
        return configMapper.selectCount(Wrappers.emptyWrapper());
    }

    @Override
    public TemplateConfigPO get(String templateCode) {
        if (StringUtils.isBlank(templateCode)) {
            throw new ServiceException("请指定导出的模版编码");
        }
        LambdaQueryWrapper<TemplateConfigPO> wrapper = Wrappers.<TemplateConfigPO>lambdaQuery().eq(TemplateConfigPO::getTemplateCode, templateCode);
        TemplateConfigPO po = configMapper.selectOne(wrapper);
        if (Objects.isNull(po) || Objects.isNull(po.getContent()) || po.getContent().length == 0) {
            throw new ServiceException("模版'" + templateCode + "'不存在");
        }
        return po;
    }

    @Override
    public InputStream getTemplate(String templateCode) {
        try {
            TemplateConfigPO po = this.get(templateCode);
            return new ByteArrayInputStream(po.getContent());
        } catch (Exception e) {
            try {
                ClassPathResource templateResource = new ClassPathResource(MessageFormat.format(TEMPLATE_PATH, templateCode));
                return templateResource.getInputStream();
            } catch (IOException ex) {
                return null;
            }
        }
    }
}
